'use strict';

const axios = require('axios');
const semver = require('semver');
const urlJoin = require('url-join');

function getNpmInfo(pkgName, registry = getNpmRegistry(true)) {
  const api = urlJoin(registry, pkgName);
  return axios
    .get(api)
    .then(res => (res.status === 200 ? res.data : null))
    .catch(error => Promise.reject(error));
}

function getVersions(pkgName, registry = getNpmRegistry(true)) {
  return getNpmInfo(pkgName, registry).then(res => Object.keys(res.versions));
}

async function getLatestVersion(pkgName, registry = getNpmRegistry(true)) {
  const res = await getNpmInfo(pkgName, registry);
  if (!res['dist-tags'] || !res['dist-tags'].latest) {
    return null;
  }
  const latestVersion = res['dist-tags'].latest;
  return latestVersion;
}

function getLatestSemverVersion(baseVersion, versions) {
  const latestVersions = versions
    .filter(version => semver.satisfies(baseVersion, `^${version}`))
    .sort((a, b) => semver.gt(b, a));
  return latestVersions[0];
}

// 根据指定 version 和包名获取符合 semver 规范的最新版本号
function getNpmLatestSemverVersion(pkgName, baseVersion, registry = getNpmRegistry(true)) {
  return getVersions(pkgName, registry).then((versions) => {
    return getLatestSemverVersion(baseVersion, versions);
  });
}

// 获取 registry 信息
function getNpmRegistry(isOriginal = true) {
  // 阿里云镜像10分钟同步一次
  return 'https://registry.npmmirror.com';
  // return isOriginal ? 'https://registry.npmmirror.com' : 'https://registry.npm.taobao.org';
}

module.exports = {
  getNpmInfo,
  getVersions,
  getNpmRegistry,
  getLatestVersion,
  getLatestSemverVersion,
  getNpmLatestSemverVersion,
};
